package com.aco.party.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * <pre>
 * 
 * @(#)BeanLocator.java 2013-08-01
 * @功能说明：
 *        spring 初始化类
 *        </pre>
 */
public final class BeanLocator {
	private static final Logger logger = LoggerFactory.getLogger(BeanLocator.class);
	private static BeanLocator instance = null;
	private static final String DEFAULT_CONFIGURATION_FILENAME = "spring-config/spring-config.xml";
	private static String configurationFileName = null;
	private ApplicationContext applicationContext = null;

	public static BeanLocator getInstance() {
		if (instance == null) {
			synchronized (logger) {
				if (instance == null)
					instance = new BeanLocator();
			}
		}
		return instance;
	}

	public static void setConfigurationFileName(String fileName) {
		configurationFileName = fileName;
	}

	private BeanLocator() {
		this.loadSpring();
	}

	public void reloadSpring() {
		this.loadSpring();
	}

	private void loadSpring() {
		if ((configurationFileName == null) || (configurationFileName.length() == 0))
			configurationFileName = DEFAULT_CONFIGURATION_FILENAME;
		try {
			this.applicationContext = null;
			this.applicationContext = new ClassPathXmlApplicationContext(configurationFileName);
		} catch (Exception e) {
			logger.error("初始化spring配置文件时发生异常:" + e.getMessage(), e);
			throw new RuntimeException("初始化spring配置文件时发生异常:" + e.getMessage(), e);
		}
	}

	public Object getBean(String beanName) {
		return this.applicationContext.getBean(beanName);
	}
}